const prisma = require('../config/database');
const formatDateTime = require('../utils/formatDateTime');

// 根据用户ID分页获取查卷审核列表
exports.getRecheckRequestList = async (req, res) => {
  try {
    const { userId, status = -1, page = 1, pageSize = 10 } = req.query;

    // 参数验证
    if (!userId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: userId'
      });
    }

    const skip = (parseInt(page) - 1) * parseInt(pageSize);
    const take = parseInt(pageSize);

    // 构建查询条件
    const whereClause = {
      subject_leader_id: parseInt(userId)
    };

    // 如果status不等于-1，则添加status条件
    if (status !== '所有状态') {
      const parsedStatus = parseInt(status);
      whereClause.status = parsedStatus;
    }

    // 查询符合条件的查卷申请
    const recheckRequests = await prisma.recheck_request.findMany({
      where: whereClause,
      orderBy: {
        request_time: 'desc' // 按申请时间降序排列
      },
      skip,
      take
    });

    // 获取总数
    const total = await prisma.recheck_request.count({
      where: whereClause
    });

    // 获取所有申请教师的ID
    const teacherIds = recheckRequests.map(request => request.request_teacher_id);

    // 查询教师信息
    const teachers = await prisma.user.findMany({
      where: {
        id: {
          in: teacherIds
        }
      },
      select: {
        id: true,
        name: true
      }
    });

    // 创建教师ID到名称的映射
    const teacherMap = {};
    teachers.forEach(teacher => {
      teacherMap[teacher.id] = teacher.name;
    });

    // 格式化查卷申请数据
    const list = recheckRequests.map(request => ({
      recheckRequestId: request.id,
      studentPaperId: request.student_paper_id,
      requestTeacherId: request.request_teacher_id,
      requestTeacherName: teacherMap[request.request_teacher_id] || '未知教师',
      studentQuestion: request.student_question,
      teacherComment: request.teacher_comment,
      requestTime: formatDateTime(request.request_time),
      status: request.status
    }));

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: {
        list,
        total
      }
    });
  } catch (error) {
    console.error('获取查卷审核列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '获取查卷审核列表失败: ' + error.message
    });
  }
};

// 学科组长根据学生试卷ID进行查卷
exports.recheckBySelf = async (req, res) => {
  try {
    const { recheckRequestId, studentPaperId, requestTeacherId } = req.body;

    // 参数验证
    if (!recheckRequestId || !studentPaperId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: recheckRequestId, studentPaperId'
      });
    }

    // 查询查卷申请信息
    const recheckRequest = await prisma.recheck_request.findUnique({
      where: { id: parseInt(recheckRequestId) }
    });

    if (!recheckRequest) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '查卷申请不存在'
      });
    }

    // 查询学生试卷信息
    const studentPaper = await prisma.student_paper.findUnique({
      where: { id: parseInt(studentPaperId) }
    });

    if (!studentPaper) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '学生试卷不存在'
      });
    }

    // 查询考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: studentPaper.examination_id }
    });

    if (!examination) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '考试不存在'
      });
    }

    // 查询学生信息
    const student = await prisma.user.findUnique({
      where: { id: studentPaper.user_id }
    });

    if (!student) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '学生不存在'
      });
    }

    // 查询学生所在班级
    const studentClass = await prisma.student_classes.findFirst({
      where: { student_id: student.id }
    });

    let classesName = '未知班级';
    if (studentClass) {
      const classInfo = await prisma.classes.findUnique({
        where: { id: studentClass.classes_id }
      });
      classesName = classInfo ? classInfo.name : '未知班级';
    }

    // 查询试卷的满分（考试计划中所有题目的总分）
    let paperFullMark = 0;
    if (examination.exam_plan_id) {
      const examPlanDetails = await prisma.exam_plan_details.findMany({
        where: { exam_plan_id: examination.exam_plan_id }
      });
      paperFullMark = examPlanDetails.reduce((total, detail) => total + (detail.score || 0), 0);
    }

    // 查询学生试卷详情
    const paperDetails = await prisma.paper_detail.findMany({
      where: { student_paper_id: parseInt(studentPaperId) },
      orderBy: { question_order: 'asc' }
    });

    // 获取所有题目的ID
    const questionIds = paperDetails.map(detail => detail.question_id);
    const questions = await prisma.question.findMany({
      where: { id: { in: questionIds } }
    });

    // 创建题目ID到信息的映射
    const questionMap = {};
    for (const question of questions) {
      questionMap[question.id] = question;
    }

    // 获取所有批改老师的ID
    const teacherIds = paperDetails.filter(detail => detail.user_id).map(detail => detail.user_id);
    const teachers = await prisma.user.findMany({
      where: { id: { in: teacherIds } }
    });

    // 创建教师ID到名称的映射
    const teacherMap = {};
    teachers.forEach(teacher => {
      teacherMap[teacher.id] = teacher.name;
    });

    // 获取所有答案信息
    const answerIds = questions.map(q => q.answer_id).filter(id => id !== null);

    // 获取主观题答案
    const subjectiveAnswers = await prisma.subjective_answers.findMany({
      where: { id: { in: answerIds } }
    });
    
    // 获取客观题答案
    const objectiveAnswers = await prisma.objective_answers.findMany({
      where: { id: { in: answerIds } }
    });
    
    // 创建答案ID到信息的映射
    const answerMap = {};
    subjectiveAnswers.forEach(answer => {
      answerMap[`subjective_${answer.id}`] = answer;
    });
    objectiveAnswers.forEach(answer => {
      answerMap[`objective_${answer.id}`] = answer;
    });

    // 处理客观题和主观题数据
    const subjective = [];
    const objective = [];

    for (const detail of paperDetails) {
      const question = questionMap[detail.question_id];
      if (!question) continue;

      // 获取大题信息
      const bigQuestion = await prisma.big_question.findUnique({
        where: { id: detail.big_question_id }
      });

      // 处理question_content，尝试将JSON字符串转换为对象
      let processedQuestionContent = question.question_content;
      try {
        if (question.question_content && typeof question.question_content === 'string' && 
            (question.question_content.startsWith('{') || question.question_content.startsWith('['))) {
          processedQuestionContent = JSON.parse(question.question_content);
        }
      } catch (error) {
        console.warn('解析题目内容JSON失败:', error);
        // 解析失败时保持原始内容
      }

      const baseInfo = {
        questionOrder: detail.question_order,
        questionId: detail.question_id,
        questionName: question.name,
        questionContent: processedQuestionContent,
        studentAnswer: detail.student_answer,
        score: bigQuestion ? await getQuestionScore(detail.big_question_id, detail.question_order, examination.exam_plan_id) : 0,
        finalScore: detail.final_score || 0
      };

      // 判断是客观题还是主观题
      if (question.answer_type_id === 1) { // 客观题
        const answer = answerMap[`objective_${question.answer_id}`];
        subjective.push({
          ...baseInfo,
          questionAnswer: answer ? answer.question_answer : ''
        });
      } else if (question.answer_type_id === 2) { // 主观题
        const answer = answerMap[`subjective_${question.answer_id}`];
        
        // 处理评分细则，将分隔符"|"的字符串转换为数组
        let gradingRulesArray = [];
        if (answer && answer.grading_rules) {
          gradingRulesArray = answer.grading_rules.split('|').filter(rule => rule.trim() !== '');
        }
        
        objective.push({
          ...baseInfo,
          checkDerail: detail.check_detail || '',
          userId: detail.user_id,
          userName: detail.user_id ? (teacherMap[detail.user_id] || '未知教师') : '',
          referenceAnswer: answer ? answer.reference_answer : '',
          gradingRules: gradingRulesArray
        });
      }
    }

    // 对subjective和objective数组按照question_order升序排列
    subjective.sort((a, b) => a.questionOrder - b.questionOrder);
    objective.sort((a, b) => a.questionOrder - b.questionOrder);

    // 组装返回数据
    const result = {
      examinationData: {
        name: examination.name,
        paperFullMark: paperFullMark
      },
      studentData: {
        name: student.name,
        account: student.account,
        classesName: classesName,
        totalScore: studentPaper.total_score || 0
      },
      subjective: subjective,
      objective: objective
    };

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: result
    });
  } catch (error) {
    console.error('获取试卷详情失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '获取试卷详情失败: ' + error.message
    });
  }
};

// 获取题目分数的辅助函数
async function getQuestionScore(bigQuestionId, questionOrder, examPlanId) {
  if (!examPlanId) return 0;
  
  const examPlanDetail = await prisma.exam_plan_details.findFirst({
    where: {
      exam_plan_id: examPlanId,
      big_question_id: bigQuestionId,
      question_order: questionOrder
    }
  });
  
  return examPlanDetail ? (examPlanDetail.score || 0) : 0;
}

// 驳回查卷申请
exports.rejectTheRequest = async (req, res) => {
  try {
    const { recheckRequestId, rejectReason, requestTeacherId, studentPaperId } = req.body;
    
    // 参数验证
    if (!recheckRequestId || !rejectReason || !requestTeacherId || !studentPaperId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: recheckRequestId, rejectReason, requestTeacherId, studentPaperId'
      });
    }

    // 查询查卷申请信息
    const recheckRequest = await prisma.recheck_request.findUnique({
      where: { id: parseInt(recheckRequestId) }
    });

    if (!recheckRequest) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '查卷申请不存在'
      });
    }

    // 查询学生试卷信息
    const studentPaper = await prisma.student_paper.findUnique({
      where: { id: parseInt(studentPaperId) }
    });

    if (!studentPaper) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '学生试卷不存在'
      });
    }

    // 查询学生信息
    const student = await prisma.user.findUnique({
      where: { id: studentPaper.user_id }
    });

    if (!student) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '学生不存在'
      });
    }

    // 创建东八区当前时间
    const now = new Date();
    const utc8Date = new Date(now.getTime() + (8 * 60 * 60 * 1000));

    // 更新查卷申请状态为"已拒绝"
    await prisma.recheck_request.update({
      where: { id: parseInt(recheckRequestId) },
      data: {
        status: 3, // 已拒绝
        reject_reason: rejectReason,
        process_time: utc8Date
      }
    });

    // 检查申请教师是否在线，如果在线则发送socket消息
    const { io, userList } = require('../index');
    const { getSocketId } = require('../utils/zym-socketIoUtils');
    
    const teacherSocketIds = getSocketId(userList, parseInt(requestTeacherId));
    
    if (teacherSocketIds && teacherSocketIds.length > 0) {
      // 教师在线，发送socket消息
      teacherSocketIds.forEach(socketId => {
        io.to(socketId).emit('requestResult', {
          message: `您的查卷申请已被拒绝：${rejectReason}`,
          requestId: recheckRequestId,
          status: 3 // 已拒绝
        });
      });
    }

    // 创建系统通知
    await prisma.system_notification.create({
      data: {
        recipient_id: parseInt(requestTeacherId),
        sender_id: null, // 系统发送的通知
        notification_type_id: 5, // 查卷申请结果通知类型
        content: `${student.account}-${student.name}的查卷申请有结果啦！`,
        is_read: 0,
        create_time: utc8Date
      }
    });

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: null
    });
    
  } catch (error) {
    console.error('驳回查卷申请失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '驳回查卷申请失败: ' + error.message
    });
  }
};

// 根据学生试卷ID查找申请驳回的原因
exports.getRejectReason = async (req, res) => {
  try {
    const { studentPaperId } = req.query;
    
    // 参数验证
    if (!studentPaperId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: studentPaperId'
      });
    }

    // 在recheck_request表中查找对应studentPaperId的记录
    const recheckRequest = await prisma.recheck_request.findFirst({
      where: { 
        student_paper_id: parseInt(studentPaperId),
        status: 3 // 已拒绝状态
      },
      select: {
        reject_reason: true
      }
    });

    if (!recheckRequest) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '未找到被驳回的查卷申请'
      });
    }

    // 返回驳回原因
    return res.status(200).json({
      code: 200,
      message: 'success',
      data: recheckRequest.reject_reason || ''
    });
    
  } catch (error) {
    console.error('获取申请驳回原因失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '获取申请驳回原因失败: ' + error.message
    });
  }
};

// 根据用户ID获取该学科的所有学科教师
exports.getSubjectTeachers = async (req, res) => {
  try {
    const { userId } = req.query;
    
    // 参数验证
    if (!userId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: userId'
      });
    }

    // 1. 查询用户教授的学科
    const teacherSubject = await prisma.teacher_classes_subject.findFirst({
      where: { teacher_id: parseInt(userId) },
      select: { subject_id: true }
    });

    if (!teacherSubject) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '未找到该教师所教授的学科'
      });
    }

    // 2. 查询同学科的所有教师
    const teachersWithSameSubject = await prisma.teacher_classes_subject.findMany({
      where: { 
        subject_id: teacherSubject.subject_id
      },
      select: {
        teacher_id: true
      }
    });
    
    // 获取这些教师的ID列表
    const teacherIds = [...new Set(teachersWithSameSubject.map(t => t.teacher_id))];
    
    // 3. 查询这些教师的详细信息
    const teachers = await prisma.user.findMany({
      where: {
        id: {
          in: teacherIds
        }
      },
      select: {
        id: true,
        name: true,
        account: true
      }
    });

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: teachers
    });
    
  } catch (error) {
    console.error('获取学科教师列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '获取学科教师列表失败: ' + error.message
    });
  }
};

// 给教师分配复审任务
exports.assignRecheckTask = async (req, res) => {
  try {
    const { selectedTeacherIds, recheckRequestId, studentPaperId } = req.body;
    
    // 参数验证
    if (!selectedTeacherIds || !Array.isArray(selectedTeacherIds) || selectedTeacherIds.length === 0 || !recheckRequestId || !studentPaperId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: selectedTeacherIds(数组), recheckRequestId, studentPaperId'
      });
    }

    // 更新recheck_request表中的状态为"审核中"
    await prisma.recheck_request.update({
      where: { id: parseInt(recheckRequestId) },
      data: {
        status: 1 // 审核中
      }
    });

    // 创建东八区当前时间
    const now = new Date();
    const utc8Date = new Date(now.getTime() + (8 * 60 * 60 * 1000));

    // 获取paper_detail表中的数据，按question_order升序排序
    const paperDetails = await prisma.paper_detail.findMany({
      where: { student_paper_id: parseInt(studentPaperId) },
      orderBy: { question_order: 'asc' }
    });

    // 为每个选定的教师创建recheck记录并添加相应的recheck_detail记录
    for (const teacherId of selectedTeacherIds) {
      // 创建recheck记录
      const newRecheck = await prisma.recheck.create({
        data: {
          recheck_request_id: parseInt(recheckRequestId),
          checker_id: parseInt(teacherId),
          assign_time: utc8Date,
          recheck_status: 0, // 待审核
          total_score: 0,
          recheck_time: null
        }
      });

      // 为每个题目创建recheck_detail记录
      for (const detail of paperDetails) {
        await prisma.recheck_detail.create({
          data: {
            recheck_id: newRecheck.id,
            student_paper_id: parseInt(studentPaperId),
            paper_detail_id: detail.id,
            final_score: 0,
            status: 0 // 待批阅
          }
        });
      }

      // 检查教师是否在线，如果在线则发送socket消息
      const { io, userList } = require('../index');
      const { getSocketId } = require('../utils/zym-socketIoUtils');
      
      const teacherSocketIds = getSocketId(userList, parseInt(teacherId));
      
      if (teacherSocketIds && teacherSocketIds.length > 0) {
        // 教师在线，发送socket消息
        teacherSocketIds.forEach(socketId => {
          io.to(socketId).emit('recheckAssignment', {
            message: '学科组长给你分配了一个复查任务，请注意查收',
            recheckRequestId: recheckRequestId
          });
        });
      }

      // 创建系统通知
      await prisma.system_notification.create({
        data: {
          recipient_id: parseInt(teacherId),
          sender_id: null, // 系统发送的通知
          notification_type_id: 9, // 复审任务通知类型
          content: '学科组长给你分配了一个复查任务，请注意查收',
          is_read: 0,
          create_time: utc8Date
        }
      });
    }

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: null
    });
    
  } catch (error) {
    console.error('分配复审任务失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '分配复审任务失败: ' + error.message
    });
  }
};

// 获取复审结果
exports.getRecheckResult = async (req, res) => {
  try {
    const { recheckRequestId } = req.query;
    
    // 参数验证
    if (!recheckRequestId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: recheckRequestId'
      });
    }

    // 查询查卷申请信息
    const recheckRequest = await prisma.recheck_request.findUnique({
      where: { id: parseInt(recheckRequestId) }
    });

    if (!recheckRequest) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '查卷申请不存在'
      });
    }

    // 查询学生试卷信息
    const studentPaper = await prisma.student_paper.findUnique({
      where: { id: recheckRequest.student_paper_id }
    });

    if (!studentPaper) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '学生试卷不存在'
      });
    }

    // 获取复审结果
    const result = {
      recheckRequestId: recheckRequest.id,
      requestTeacherId: recheckRequest.request_teacher_id,
      subjectLeaderId: recheckRequest.subject_leader_id,
      studentPaperId: recheckRequest.student_paper_id,
      originalScore: recheckRequest.original_score || studentPaper.total_score || 0,
      finalScore: recheckRequest.final_score || studentPaper.total_score || 0,
      status: recheckRequest.status
    };

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: result
    });
    
  } catch (error) {
    console.error('获取复审结果失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '获取复审结果失败: ' + error.message
    });
  }
};

// 发送复审结果给申请查卷的教师
exports.recoverRecheckResult = async (req, res) => {
  try {
    const { 
      recheckRequestId, 
      originalScore, 
      finalScore, 
      resultSummary, 
      subjectLeaderId, 
      requestTeacherId, 
      studentPaperId 
    } = req.body;
    
    // 参数验证
    if (!recheckRequestId || originalScore === undefined || finalScore === undefined || 
        !resultSummary || !subjectLeaderId || !requestTeacherId || !studentPaperId) {
      return res.status(400).json({
        code: 400,
        message: 'error',
        data: '缺少必要参数: recheckRequestId, originalScore, finalScore, resultSummary, subjectLeaderId, requestTeacherId, studentPaperId'
      });
    }

    // 创建东八区当前时间
    const now = new Date();
    const utc8Date = new Date(now.getTime() + (8 * 60 * 60 * 1000));

    // 在recheck_result表中添加一条新记录
    await prisma.recheck_result.create({
      data: {
        recheck_request_id: parseInt(recheckRequestId),
        original_score: parseFloat(originalScore),
        final_score: parseFloat(finalScore),
        result_summary: resultSummary,
        created_by_id: parseInt(subjectLeaderId),
        create_time: utc8Date
      }
    });

    // 更新查卷申请状态为已完成(4)
    await prisma.recheck_request.update({
      where: { id: parseInt(recheckRequestId) },
      data: {
        status: 4, // 已完成状态更新为4
        process_time: utc8Date
      }
    });
    
    // 获取学生试卷相关信息
    const studentPaper = await prisma.student_paper.findUnique({
      where: { id: parseInt(studentPaperId) }
    });

    if (!studentPaper) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '学生试卷不存在'
      });
    }

    // 获取学生信息
    const student = await prisma.user.findUnique({
      where: { id: studentPaper.user_id }
    });

    if (!student) {
      return res.status(404).json({
        code: 404,
        message: 'error',
        data: '学生不存在'
      });
    }

    // 检查申请教师是否在线，如果在线则发送socket消息
    const { io, userList } = require('../index');
    const { getSocketId } = require('../utils/zym-socketIoUtils');
    
    const teacherSocketIds = getSocketId(userList, parseInt(requestTeacherId));
    
    if (teacherSocketIds && teacherSocketIds.length > 0) {
      // 教师在线，发送socket消息
      teacherSocketIds.forEach(socketId => {
        io.to(socketId).emit('recheckResult', {
          message: `学生${student.account}-${student.name}的查卷申请已完成，请查看结果`,
          requestId: recheckRequestId,
          status: 2 // 已完成
        });
      });
    }

    // 创建系统通知
    await prisma.system_notification.create({
      data: {
        recipient_id: parseInt(requestTeacherId),
        sender_id: null, // 系统发送的通知
        notification_type_id: 5, // 查卷申请结果通知类型
        content: `${student.account}-${student.name}的查卷申请有结果啦！`,
        is_read: 0,
        create_time: utc8Date
      }
    });


    return res.status(200).json({
      code: 200,
      message: 'success',
      data: null
    });
    
  } catch (error) {
    console.error('发送复审结果失败:', error);
    return res.status(500).json({
      code: 500,
      message: 'error',
      data: '发送复审结果失败: ' + error.message
    });
  }
};
